package com.atguigu.gulimall.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

/**
 * 解决跨域问题的filter
 *
 * 配置跨域规则
 *
 * 出现问题：he 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:8001, http://localhost:8001', but only one is allowed.
 * 原因：由于gateway使用的是webflux，而不是springmvc，所以需要先关闭webflux的cors，再从gateway的filter里边设置cors就行了。
 * 修改gateway的配置，增加:
 *      filters:
 *        - RewritePath=/api/(?<segment>.*), /renren-fast/$\{segment}
 *        - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin
 */
@Configuration
public class GulimallCorsConfiguration {

    @Bean
    public CorsWebFilter corsWebFilter() {
        // 找到它的实现UrlBasedCorsConfigurationSource,导包要选择reactive包下的
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 配置跨域
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        // corsConfiguration.addAllowedOrigin("http://localhost:8001");
        // corsConfiguration.setAllowedOrigins(Arrays.asList("*"));
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.setAllowCredentials(true); // 是否允许携带Cookie跨域

        // 任意路径都生效
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsWebFilter(source);
    }
}
